package com.aaa.marketresearch.webclient.gwt.util;

import com.google.gwt.http.client.*;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONParser;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Nail
 */
public abstract class Requester {

    private List<Responder> responders = new ArrayList<>();

    public void addResponder(Responder responder) {
        responders.add(responder);
    }

    // sendData
    protected void doPostRequest(String url) {
        this.doPostRequest(url, null);
    }

    // sendData
    protected void doPostRequest(String url, String postData) {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,url);
        builder.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        try {
            builder.sendRequest(postData, new RequestCallback() {
                @Override
                public void onError(Request request, Throwable exception) {
                    ConsoleLog.getInstance().error("loadData onError: " + exception);
                }
                @Override
                public void onResponseReceived(Request request, Response response) {
                    if (200 == response.getStatusCode()) {
                        String content = response.getText();
                        ConsoleLog.getInstance().debug("loadDataResponse " + content);
                        for (Responder responder : responders) {
                            responder.handleGetResponse(content);
                        }
                    }
                }
            });
        } catch (RequestException exception) {
            ConsoleLog.getInstance().error("sendData catch error: " + exception);
        }
    }



}
